package com.zhongfl.crm.service.impl;

import com.zhongfl.crm.mapper.LxRevisitLogMapperCRM;
import com.zhongfl.crm.model.LxRevisitLog;
import com.zhongfl.crm.model.vo.LxRevisitLogCommentVO;
import com.zhongfl.crm.model.vo.LxRevisitLogVO;
import com.zhongfl.crm.service.LxRevisitLogServiceCRM;
import org.springframework.stereotype.Service;
import tech.heptagram.staff.cas.common.AssertUtils;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 跟进记录 服务实现类
 *
 * @author tiantian
 * @date 2018/9/20 19:51
 */
@Service
public class LxRevisitLogServiceCRMImpl implements LxRevisitLogServiceCRM {
    @Resource
    private LxRevisitLogMapperCRM lxRevisitLogMapperCRM;

    @Override
    public void insert(LxRevisitLog lxRevisitLog) {
        AssertUtils.notNull(lxRevisitLog,"跟进记录为空！");
        lxRevisitLogMapperCRM.insertSelective(lxRevisitLog);
    }

    @Override
    public void deleteById(Long id) {
        AssertUtils.notNull(id,"跟进记录ID为空！");
        lxRevisitLogMapperCRM.deleteById(id);
    }

    @Override
    public void updateById(LxRevisitLog lxRevisitLog) {
        AssertUtils.notNull(lxRevisitLog,"跟进记录为空！");
        AssertUtils.notNull(lxRevisitLog.getId(),"跟进记录ID为空！");
        lxRevisitLogMapperCRM.updateByIdSelective(lxRevisitLog);
    }

    @Override
    public LxRevisitLog findById(Long id) {
        AssertUtils.notNull(id,"跟进记录ID为空！");
        return lxRevisitLogMapperCRM.selectById(id);
    }

    @Override
    public List<LxRevisitLogVO> findByLoggableIdAndLoggableType(Long loggableId, String loggableType) {
        AssertUtils.notNull(loggableId,"跟进记录关联对象ID为空！");
        AssertUtils.hasText(loggableType,"跟进记录关联对象类型为空！");
        List<LxRevisitLogVO> lxRevisitLogVOs = lxRevisitLogMapperCRM.selectByLoggableIdAndLoggableType(loggableId, loggableType);

        for (LxRevisitLogVO lxRevisitLogVO : lxRevisitLogVOs) {
            List<LxRevisitLogCommentVO> collect = lxRevisitLogVO.getComments().stream()
                    .sorted(Comparator.comparing(LxRevisitLogCommentVO::getCreatedAt))
                    .collect(Collectors.toList());
            lxRevisitLogVO.setComments(collect);
        }

        return lxRevisitLogVOs;
    }
}
